package com.scmt.hmzd.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.scmt.base.utils.BASE64DecodedMultipartFile;
import com.scmt.hmzd.entity.HmProjectTechnician;
import com.scmt.hmzd.service.IHmProjectTechnicianService;
import com.scmt.hmzd.service.IHmTechnicianService;

import javax.servlet.http.HttpServletResponse;

import com.scmt.hmzd.utils.UploadFileUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.beans.factory.annotation.Autowired;
import com.scmt.core.common.utils.ResultUtil;
import com.scmt.core.common.vo.PageVo;
import com.scmt.core.common.vo.Result;
import com.scmt.core.common.vo.SearchVo;
import com.scmt.core.common.utils.SecurityUtil;
import com.scmt.hmzd.entity.HmTechnician;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.scmt.core.common.enums.LogType;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author
 **/
@RestController
@Api(tags = " 技师信息管理数据接口")
@RequestMapping("/scmt/hmTechnician")
public class HmTechnicianController {
    @Autowired
    private IHmTechnicianService hmTechnicianService;
    @Autowired
    private IHmProjectTechnicianService iHmProjectTechnicianService;

    /**
     * 功能描述：新增技师信息管理数据
     *
     * @param hmTechnician 实体
     * @return 返回新增结果
     */
    @ApiOperation("新增技师信息管理数据")
    @PostMapping("addHmTechnician")
    public Result<Object> addHmTechnician(@RequestBody HmTechnician hmTechnician) {
        try {
            hmTechnician.setDelFlag(0);
            hmTechnician.setCreateTime(new Date());
            if (StringUtils.isNotBlank(hmTechnician.getWorkImg())) {
                MultipartFile imgFile = BASE64DecodedMultipartFile.base64ToMultipart(hmTechnician.getWorkImg());
                String fileUrl = UploadFileUtils.uploadFile(imgFile);
                hmTechnician.setWorkImg(fileUrl);
            }
            if (StringUtils.isNotBlank(hmTechnician.getCover())) {
                MultipartFile imgFile = BASE64DecodedMultipartFile.base64ToMultipart(hmTechnician.getCover());
                String fileUrl = UploadFileUtils.uploadFile(imgFile);
                hmTechnician.setCover(fileUrl);
            }
            boolean res = hmTechnicianService.save(hmTechnician);
            if (res) {
                if(hmTechnician.getProjectList() != null) {
                    ArrayList<HmProjectTechnician> hmProjectTechnicians = new ArrayList<>();
                    for (String s : hmTechnician.getProjectList()) {
                        HmProjectTechnician hmProjectTechnician = new HmProjectTechnician();
                        hmProjectTechnician.setTechnicianId(hmTechnician.getId());
                        hmProjectTechnician.setProjectId(s);
                        hmProjectTechnicians.add(hmProjectTechnician);
                    }
                    iHmProjectTechnicianService.saveBatch(hmProjectTechnicians);
                }
                return ResultUtil.data(res, "保存成功");
            } else {
                return ResultUtil.data(res, "保存失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error("保存异常:" + e.getMessage());
        }
    }

    /**
     * 功能描述：更新数据
     *
     * @param hmTechnician 实体
     * @return 返回更新结果
     */
    @ApiOperation("更新技师信息管理数据")
    @PostMapping("updateHmTechnician")
    public Result<Object> updateHmTechnician(@RequestBody HmTechnician hmTechnician) {
        if (StringUtils.isBlank(hmTechnician.getId())) {
            return ResultUtil.error("参数为空，请联系管理员！！");
        }
        try {
            //是否有路径
            if (!StringUtils.isBlank(hmTechnician.getWorkImg()) && hmTechnician.getWorkImg().indexOf(";base64") > -1) {
                //base64 转文件
                MultipartFile imgFile = BASE64DecodedMultipartFile.base64ToMultipart(hmTechnician.getWorkImg());
                String fileUrl = UploadFileUtils.uploadFile(imgFile);
                hmTechnician.setWorkImg(fileUrl);
            }
            if (!StringUtils.isBlank(hmTechnician.getCover()) && hmTechnician.getCover().indexOf(";base64") > -1) {
                //base64 转文件
                MultipartFile imgFile = BASE64DecodedMultipartFile.base64ToMultipart(hmTechnician.getCover());
                String fileUrl = UploadFileUtils.uploadFile(imgFile);
                hmTechnician.setCover(fileUrl);
            }
            boolean res = hmTechnicianService.updateById(hmTechnician);
            if (res) {
                QueryWrapper<HmProjectTechnician> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("technician_id", hmTechnician.getId());
                iHmProjectTechnicianService.remove(queryWrapper);
                if(hmTechnician.getProjectList() != null) {
                    ArrayList<HmProjectTechnician> hmProjectTechnicians = new ArrayList<>();
                    for (String s : hmTechnician.getProjectList()) {
                        HmProjectTechnician hmProjectTechnician = new HmProjectTechnician();
                        hmProjectTechnician.setTechnicianId(hmTechnician.getId());
                        hmProjectTechnician.setProjectId(s);
                        hmProjectTechnicians.add(hmProjectTechnician);
                    }
                    iHmProjectTechnicianService.saveBatch(hmProjectTechnicians);
                }
                return ResultUtil.data(res, "修改成功");
            } else {
                return ResultUtil.data(res, "修改失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error("保存异常:" + e.getMessage());
        }
    }

    /**
     * 功能描述：根据主键来删除数据
     *
     * @param ids 主键集合
     * @return 返回删除结果
     */
    @ApiOperation("根据主键来删除技师信息管理数据")
    @PostMapping("deleteHmTechnician")
    public Result<Object> deleteHmTechnician(@RequestParam String[] ids) {
        if (ids == null || ids.length == 0) {
            return ResultUtil.error("参数为空，请联系管理员！！");
        }
        try {
            boolean res = hmTechnicianService.removeByIds(Arrays.asList(ids));
            if (res) {
                return ResultUtil.data(res, "删除成功");
            } else {
                return ResultUtil.data(res, "删除失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error("删除异常:" + e.getMessage());
        }
    }

    /**
     * 功能描述：根据主键来获取数据
     *
     * @param id 主键
     * @return 返回获取结果
     */
    @ApiOperation("根据主键来获取技师信息管理数据")
    @GetMapping("getHmTechnician")
    public Result<Object> getHmTechnician(@RequestParam(name = "id") String id) {
        if (StringUtils.isBlank(id)) {
            return ResultUtil.error("参数为空，请联系管理员！！");
        }
        try {
            HmTechnician res = hmTechnicianService.getById(id);
            if (res != null) {
                QueryWrapper<HmProjectTechnician> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("technician_id", res.getId());
                List<HmProjectTechnician> list = iHmProjectTechnicianService.list(queryWrapper);
                if(list != null) {
                    List<String> collect = list.stream().map(item -> item.getProjectId()).collect(Collectors.toList());
                    res.setProjectList(collect);
                }
                return ResultUtil.data(res, "查询成功");
            } else {
                return ResultUtil.data(res, "查询失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error("查询异常:" + e.getMessage());
        }
    }

    /**
     * 功能描述：实现分页查询
     *
     * @param searchVo 需要模糊查询的信息
     * @param pageVo   分页参数
     * @return 返回获取结果
     */
    @ApiOperation("分页查询技师信息管理数据")
    @GetMapping("queryHmTechnicianList")
    public Result<Object> queryHmTechnicianList(HmTechnician hmTechnician, SearchVo searchVo, PageVo pageVo) {
        try {
            IPage<HmTechnician> result = hmTechnicianService.queryHmTechnicianListByPage(hmTechnician, searchVo, pageVo);
            return ResultUtil.data(result);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error("查询异常:" + e.getMessage());
        }
    }

    /**
     * 功能描述：导出数据
     *
     * @param response     请求参数
     * @param hmTechnician 查询参数
     * @return
     */
    @ApiOperation("导出技师信息管理数据")
    @PostMapping("/download")
    public void download(HttpServletResponse response, HmTechnician hmTechnician) {
        try {
            hmTechnicianService.download(hmTechnician, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
